package str.slide;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * @author : Rookie
 * @description : 最长无重复字串
 * @date : 2023/9/12
 */
public class LongestNoRepeatSubStr {

    public static void main(String[] args) {
        String str = "davgbtascewqwec";
        int result1 = solve1(str);
        int result2 = solve2(str);
        System.out.println(result1);
        System.out.println(result2);
    }

    private static int solve1(String str) {
        int low =0,result=0;
        Map<Character, Integer> hashMap = new HashMap<>(str.length());
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (hashMap.containsKey(c)) {
                System.out.println("low的值是：" + low +",当前字符是："+c+"，上次出现的索引是" + hashMap.get(c));
                low = Math.max(low,hashMap.get(c) +1);
            }
            hashMap.put(c,i);
            result = Math.max(result,i-low);
        }
        return result;
    }

    private static int solve2(String str) {
        int left =0,right =0,result =0;
        HashSet<Character> hashSet = new HashSet<>(str.length());
        while (right<str.length()) {
            char c = str.charAt(right);
            if (hashSet.contains(c)) {
                // 移动左侧窗口
                hashSet.remove(str.charAt(left));
                left++;
            } else {
                hashSet.add(c);
                result = Math.max(result,right-left);
                right++;
            }
        }
        return result;
    }
}
